﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using BO;
using System.Text;
using Microsoft.Reporting.WebForms;
using System.Drawing.Printing;

namespace WebMotel.print
{
    public partial class printComanda : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    if (Request.QueryString["comandaID"] != null)
                    {
                        int comandaID = int.Parse(Request.QueryString["comandaID"]);

                        //rptViewer1.SizeToReportContent = true;
                        //System.Drawing.Printing.PageSettings pg = new PageSettings();
                        //// Set margins
                        //pg.Margins = new System.Drawing.Printing.Margins(100, 100, 100, 100);

                        //// Set paper size
                        //int altura = 600;


                        this.rptViewer1.LocalReport.DataSources.Clear();
                        //this.rptViewer1.Reset();
                        this.rptViewer1.ResetPageSettings();

                        //rptViewer1.ProcessingMode = ProcessingMode.Local;
                        //rptViewer1.LocalReport.ReportPath = Server.MapPath("relatorios/rptComanda.rdlc");

                        System.Drawing.Printing.PageSettings pg = new System.Drawing.Printing.PageSettings();
                        pg.Margins.Top = 100;
                        pg.Margins.Bottom = 100;
                        pg.Margins.Left = 100;
                        pg.Margins.Right = 100;
                        pg.Landscape = false;
                        System.Drawing.Printing.PaperSize size = new PaperSize();
                        size.RawKind = (int)PaperKind.A4;
                        pg.PaperSize = size;
                        this.rptViewer1.SetPageSettings(pg);

                        Comanda comanda = ComandaBO.Selecionar(comandaID);


                        string entrada = ("Entrada   : " + comanda.dtHoraEntrada.Value.ToString());
                        string saida = "";
                        string tempDecorrido = "";
                        if (comanda.dtHoraSaida != null)
                        {
                            saida = ("Saída      : " + comanda.dtHoraSaida.Value.ToString());

                            TimeSpan timeSpan = comanda.dtHoraSaida.Value.Subtract(comanda.dtHoraEntrada.Value);

                            int horasDecorridas = timeSpan.Hours;
                            if (timeSpan.Days > 0)
                            {
                                for (int i = 0; i <= timeSpan.Days; i++)
                                    horasDecorridas += 24;
                            }
                            string horas = horasDecorridas.ToString().PadLeft(2, '0');
                            string Minutes = timeSpan.Minutes.ToString().PadLeft(2, '0');
                            string Seconds = timeSpan.Seconds.ToString().PadLeft(2, '0');


                            string tempo = horas + ":" + Minutes + ":" + Seconds;

                            tempDecorrido = "Tempo Decorrido : " + tempo;
                        }


                        var pedidos = (from a in PedidoBO.Listar(0, comanda.id)
                                       select new
                                       {
                                           Descricao = a.Produto.descricao,
                                           Qtd = a.quantidade,
                                           vlrUnitario = a.valorUnitario,
                                           total = a.quantidade * a.valorUnitario
                                       }).ToList();


                        string itens = "";
                        itens = ("DESCRIÇÃO      QTD.  VL.UN.(R$)     TOTAL") + Environment.NewLine + Environment.NewLine;

                        decimal? total = 0;

                        foreach (var item in pedidos)
                        {
                            itens += (item.Descricao) + Environment.NewLine;

                            StringBuilder texto = new StringBuilder();

                            texto.Append(item.Qtd.ToString().PadLeft(3, '0') + "  x  ");
                            texto.Append(item.vlrUnitario.ToString());
                            texto.Append(" = " + item.total.ToString());

                            itens += (texto.ToString().Trim()) + Environment.NewLine;
                            total += item.total;
                            //altura += 120;
                        }

                        itens += Environment.NewLine;
                        if (comanda.valorDesconto > 0)
                        {
                            itens += ("SUB TOTAL (R$)= " + total.ToString()) + Environment.NewLine; ;
                            itens += ("Desconto (R$) = " + comanda.valorDesconto.ToString()) + Environment.NewLine;
                            itens += ("TOTAL (R$)    = " + (total - comanda.valorDesconto).ToString()) + Environment.NewLine;
                        }
                        else
                            itens += ("TOTAL (R$)    = " + total.ToString() + Environment.NewLine);

                        string rodape = ("ADOS - SysMotel v1.0 2014.01.02") + Environment.NewLine;
                        rodape += ("Impressão: " + DateTime.Now.ToString()) + Environment.NewLine;


                        Microsoft.Reporting.WebForms.ReportParameter[] parameters = new Microsoft.Reporting.WebForms.ReportParameter[7];
                        parameters[0] = new Microsoft.Reporting.WebForms.ReportParameter("apt", comanda.Acomodacao.AcomodacaoTipo.descricao + " - " + comanda.Acomodacao.nome);
                        parameters[1] = new Microsoft.Reporting.WebForms.ReportParameter("comandaID", comanda.id.ToString());
                        parameters[2] = new Microsoft.Reporting.WebForms.ReportParameter("entrada", entrada);
                        parameters[3] = new Microsoft.Reporting.WebForms.ReportParameter("saida", saida);
                        parameters[4] = new Microsoft.Reporting.WebForms.ReportParameter("tempoDecorrido", tempDecorrido);
                        parameters[5] = new Microsoft.Reporting.WebForms.ReportParameter("pedidos", itens);
                        parameters[6] = new Microsoft.Reporting.WebForms.ReportParameter("rodape", rodape);


                        this.rptViewer1.LocalReport.SetParameters(parameters);


                        Microsoft.Reporting.WebForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WebForms.ReportDataSource();
                        rprtDTSource.Name = "dataSetPedidos";
                        rprtDTSource.Value = PaginaBase.LINQToDataTable(BO.PedidoBO.Listar(0, comandaID));
                        this.rptViewer1.LocalReport.DataSources.Add(rprtDTSource);



                        //reportViewer1.LocalReport.GetDefaultPageSettings().PaperSize.Height = 100;


                        this.rptViewer1.LocalReport.Refresh();
                        //this.rptViewer1.RefreshReport();


                        Warning[] warnings;
                        string[] streamIds;
                        string mimeType = string.Empty;
                        string encoding = string.Empty;
                        string extension = string.Empty;

                        byte[] bytes = rptViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = mimeType;
                        Response.AddHeader("content-disposition", "attachment; filename= comanda_" + comanda.id.ToString().PadLeft(6, '0') + "." + extension);
                        Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
                        Response.Flush(); // send it to the client to download  
                        Response.End();

                    }
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

    }
}